<script setup>
import { ref, reactive, getCurrentInstance, nextTick, watch, computed, provide, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import { ElMessageBox, ElMessage } from 'element-plus'
import { useTokenStore } from "@/stores/token";
import { getUserSpaceService, updateUserNameService } from "@/api/user.js"
import UpdateAvatar from '@/components/UpdateAvatar.vue'
import UpdatePassword from '@/components/UpdatePassword.vue'
import defaultAvatar from '@/assets/default_avatar.png';
import { useUserSpace } from "@/assets/js/file.list.js";

const userVO = useTokenStore();
const userInfo = computed(() => {
  return {
    nickName: userVO.token.nickName,
    avatar: userVO.token.qqAvatar,
    admin: userVO.token.admin
  }
});

const router = useRouter();
const route = useRoute();

// 控制上传任务窗口显示/隐藏的状态
const showUploaderWindow = ref(false);

// 提供给子组件的状态和方法
provide('showUploaderWindow', showUploaderWindow);

// 使用用户空间管理功能
const {
  userSpace,
  spacePercentage,
  formatSpaceText,
  getUseSpace
} = useUserSpace();

// 提供刷新空间的方法给子组件
provide('refreshUserSpace', getUseSpace);

const menus = [
  {
    icon: "cloud",
    name: "首页",
    menuCode: "main",
    path: "/main/all",
    allShow: true,
    children: [
      {
        icon: "all",
        name: "全部",
        category: "all",
        path: "/main/all"
      },
      {
        icon: "video",
        name: "视频",
        category: "video",
        path: "/main/video"
      },
      {
        icon: "music",
        name: "音频",
        category: "music",
        path: "/main/music"
      },
      {
        icon: "image",
        name: "图片",
        category: "image",
        path: "/main/image"
      },
      {
        icon: "doc",
        name: "文档",
        category: "doc",
        path: "/main/doc"
      },
      {
        icon: "zip",
        name: "压缩包",
        category: "zip",
        path: "/main/zip"
      },
      {
        icon: "more",
        name: "其他",
        category: "others",
        path: "/main/others"
      }
    ]
  },
  {
    path: "/myshare",
    icon: "share",
    name: "分享",
    menuCode: "share",
    allShow: true,
    children: [
      {
        name: "分享记录",
        path: "/myshare"
      }
    ]
  },
  {
    path: "/recycle",
    icon: "del",
    name: "回收站",
    menuCode: "recycle",
    tips: "回收站为你保存10天内删除的文件",
    allShow: true,
    children: [
      {
        name: "删除的文件",
        path: "/recycle"
      }
    ]
  },
  {
    path: "/settings/fileList",
    icon: "settings",
    name: "设置",
    menuCode: "settings",
    children: [
      {
        name: "用户文件",
        path: "/settings/fileList"
      },
      {
        name: "用户管理",
        path: "/settings/userList"
      }
    ]
  }
];
const currentMenu = ref({});
const currentPath = ref();
const jump = (data) => {
  if (!data.path || data.menuCode == currentMenu.value.menuCode) {
    return;
  }
  router.push(data.path);
};
const setMenu = (menuCode, path) => {
  const menu = menus.find((item) => {
    return item.menuCode === menuCode;
  });
  currentMenu.value = menu;
  currentPath.value = path;
};

watch(
  () => route,
  (newVal, oldVal) => {
    if (newVal.meta.menuCode) {
      setMenu(newVal.meta.menuCode, newVal.path);
    }
  },
  { immediate: true, deep: true }
);

const updateAvatarRef = ref()
const openUpdateAvatar = () => {
  updateAvatarRef.value.open()
}

const updatePasswordRef = ref()
const openUpdatePassword = () => {
  updatePasswordRef.value.open()
}

const openUpdateNickName = () => {
  ElMessageBox.prompt('请输入新昵称', '修改昵称', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (value) => {
      if (!value.trim()) {
        return '昵称不能为空';
      }
      if (value.length > 20) {
        return '昵称不能超过20个字符';
      }
      return true;
    }
  }).then(async ({ value }) => {
    try {
      await updateUserNameService(value);
      userVO.token.nickName = value;
      ElMessage({
        type: 'success',
        message: '昵称修改成功'
      });
    } catch (error) {
      ElMessage({
        type: 'error',
        message: '昵称修改失败: ' + (error.message || '未知错误')
      });
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消修改'
    });
  });
}

const handleCommand = async (command) => {
  if (command == 'logout') {
    try {
      await ElMessageBox.confirm(
        '你确定要退出登录吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      userVO.removeToken()
      router.push('/login')
      ElMessage({
        type: 'success',
        message: '退出登录成功',
      })
    } catch (error) {
      // 修复：检查错误类型，只有用户点击取消时才显示取消消息
      if (error === 'cancel' || error === 'close') {
        ElMessage({
          type: 'info',
          message: '已取消退出登录',
        });
      } else {
        // 其他错误情况
        ElMessage({
          type: 'error',
          message: '退出登录失败',
        });
      }
    }
  } else if (command === 'updateNickName') {
    openUpdateNickName()
  } else if (command === 'updatePassword') {
    openUpdatePassword()
  } else if (command === 'updateAvatar') {
    openUpdateAvatar()
  }
}

// 控制上传任务窗口显示和隐藏的方法
const toggleUploaderWindow = () => {
  showUploaderWindow.value = !showUploaderWindow.value;
};

onMounted(() => {
  getUseSpace();
});
</script>

<template>
  <div class="home">
    <div class="header">
      <div class="logo">
        <img src="../assets/logo.png" alt="" class="icon-pan">
        <div class="name">云忆匣</div>
      </div>
      <div class="right-panel">
        <!-- 控制上传任务窗口的按钮，独立于用户信息 -->
        <el-button size="small" type="primary" @click="toggleUploaderWindow" style="margin-right: 20px;">
          <span class="iconfont icon-transfer" style="margin-right: 5px;"></span>
          {{ showUploaderWindow ? '隐藏' : '显示' }}上传任务
        </el-button>

        <!-- 用户信息下拉菜单 -->
        <el-dropdown @command="handleCommand">
          <div class="user-info">
            <div class="avatar"><img :src="userInfo.avatar || defaultAvatar" alt="用户头像"></div>
            <span class="nick-name">{{ userInfo.nickName }}</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="updateNickName">修改昵称</el-dropdown-item>
              <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
              <el-dropdown-item command="updateAvatar">修改头像</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="body">
      <div class="left-sider">
        <div class="menu-list">
          <template v-for="item in menus">
            <div @click="jump(item)" :class="[
              'menu-item',
              item.menuCode === currentMenu.menuCode ? 'active' : '',
            ]" v-if="item.menuCode !== 'settings' || userInfo.admin === 1">
              <div :class="['iconfont', 'icon-' + item.icon]"></div>
              <div class="text">{{ item.name }}</div>
            </div>
          </template>
        </div>
        <div class="menu-sub-list">
          <div @click="jump(sub)" :class="['menu-item-sub', currentPath === sub.path ? 'active' : '']"
            v-for="sub in currentMenu.children">
            <span :class="['iconfont', 'icon-' + sub.icon]" v-if="sub.icon"></span>
            <span class="text">{{ sub.name }}</span>
          </div>
          <div class="tips" v-if="currentMenu && currentMenu.tips">
            {{ currentMenu.tips }}
          </div>
          <div class="space-info">
            <div class="space-use">
              <span>空间使用</span>
            </div>
            <el-progress :percentage="spacePercentage" color="#409eff" />
            <div class="space-text">
              <span>{{ formatSpaceText }}</span>
              <span class="iconfont icon-refresh" @click="getUseSpace"></span>
            </div>
          </div>
        </div>
      </div>
      <div class="body-content">
        <router-view v-slot="{ Component }">
          <component :is="Component"></component>
        </router-view>
        <UpdateAvatar ref="updateAvatarRef" />
        <UpdatePassword ref="updatePasswordRef" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.header {
  box-shadow: 0 3px 10px 0 rgb(0 0 0 / 6%);
  height: 56px;
  padding-left: 24px;
  padding-right: 24px;
  position: relative;
  z-index: 200;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;

  .icon-pan {
    width: 30px;
    /* 调整宽度 */
    height: 30px;
    /* 调整高度 */
  }

  .name {
    font-weight: bold;
    margin-left: 10px;
    font-size: 20px;
    /* 调整为 20px */
    color: #05a1f5;
  }
}

.right-panel {
  display: flex;
  align-items: center;

  .icon-transfer {
    cursor: pointer;
    margin-right: 50px;
  }

  .user-info {
    margin-right: 10px;
    display: flex;
    align-items: center;
    cursor: pointer;

    .avatar {
      margin: 0px 20px 0px 20px;
      width: 50px;
      height: 50px;
      border-radius: 50%;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .nick-name {
      color: #05a1f5;
      font-size: 16px;
      margin-bottom: 10px;
      margin-right: 20px;
    }
  }
}

.body {
  display: flex;
  height: calc(100vh - 56px); // 限制 body 高度

  /* 左侧侧边栏 */
  .left-sider {
    border-right: 1px solid #ddd;
    box-shadow: 2px 0 6px rgba(0, 0, 0, 0.1);
    display: flex;

    /* 主菜单列表 */
    .menu-list {
      height: calc(100vh - 56px);
      width: 80px;
      box-shadow: 1px 0 4px rgba(0, 0, 0, 0.1);
      border-right: 1px solid #e0e0e0;

      /* 菜单项 */
      .menu-item {
        text-align: center;
        font-size: 14px;
        font-weight: bold;
        padding: 20px 0;
        cursor: pointer;

        &:hover {
          background: #f3f3f3;
        }

        /* 图标样式 */
        .iconfont {
          font-weight: normal;
          font-size: 28px;
        }
      }

      /* 激活状态 */
      .active {
        .iconfont {
          color: #06a7ff;
        }

        .text {
          color: #06a7ff;
        }
      }
    }

    /* 子菜单列表 */
    .menu-sub-list {
      width: 200px;
      padding: 20px 10px 0;
      position: relative;

      /* 子菜单项 */
      .menu-item-sub {
        line-height: 40px;
        border-radius: 5px;
        cursor: pointer;
        padding-left: 66px;

        &:hover {
          background: #f3f3f3;
        }

        .iconfont {
          font-size: 20px;
          margin-right: 20px;
        }

        .text {
          font-size: 13px;
        }
      }

      /* 子菜单激活状态 */
      .active {
        background: #fff3e0;

        .iconfont {
          color: #ff9800;
        }

        .text {
          color: #ff9800;
        }
      }
    }

    /* 提示文本 */
    .tips {
      margin-top: 10px;
      color: #888888;
      font-size: 13px;
    }

    /* 空间信息（底部） */
    .space-info {
      position: absolute;
      bottom: 10px;
      width: calc(100% - 25px);
      padding: 0 5px;

      .space-use {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;
        margin-bottom: 5px;

        .icon-refresh {
          cursor: pointer;
          color: #05a1f5;
        }
      }

      .space-text {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #777;
        margin-top: 5px;

        .icon-refresh {
          cursor: pointer;
          color: #05a1f5;
        }
      }
    }
  }

  /* 主体内容区域 */
  .body-content {
    flex: 1;
    width: 0;
    padding: 20px;
    overflow: auto; // 允许内容滚动
  }
}
</style>